#include "SegmentManager.h"
#include "DB.h"

SegmentManager::SegmentManager(SegmentInventory& segInventory) : nextSegmentId(2), segmentInventory(segInventory)
{
    SEM_CREATE(semManager_lock);
}

Segment& SegmentManager::createSegment()
{
    SEM_WRITELOCK(semManager_lock);
    Segment* seg = new Segment(this->nextSegmentId++, DB::getDB().getBufferManager(), this->segmentInventory);
    this->segments.push_back(seg);
    SEM_UNLOCK(semManager_lock);
    return *seg;
}

void SegmentManager::removeSegment(Segment& segment)
{
    SEM_WRITELOCK(semManager_lock);
    for (unsigned i = 0; i < this->segments.size(); i++)
    {

        if (this->segments[i] == &segment)
        {
            this->segments.erase(this->segments.begin() + i);
        }
    }
    SEM_UNLOCK(semManager_lock);

    delete &segment;
}

SegmentManager::~SegmentManager()
{
    for (unsigned i = 0; i < this->segments.size(); i++)
    {
        delete this->segments[i];
    }
    SEM_DESTROY(semManager_lock);
}
